package com.sssre.lttcloud.codegen.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JDBC工具类
 */
@Component
public class JdbcUtils {

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 获取数据库连接
     */
    private Connection getConnection() throws SQLException {
        try {
            Class.forName(driverClassName);
            return DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            throw new SQLException("数据库驱动加载失败", e);
        }
    }

    /**
     * 执行查询SQL，返回List<Map<String, Object>>
     */
    public List<Map<String, Object>> queryForList(String sql, Object... params) throws SQLException {
        List<Map<String, Object>> result = new ArrayList<>();
        
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }
            
            // 执行查询
            try (ResultSet rs = stmt.executeQuery()) {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                
                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();
                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = metaData.getColumnName(i);
                        Object value = rs.getObject(i);
                        row.put(columnName, value);
                    }
                    result.add(row);
                }
            }
        }
        
        return result;
    }

    /**
     * 执行查询SQL，返回List<Map<String, Object>>（无参数）
     */
    public List<Map<String, Object>> queryForList(String sql) throws SQLException {
        return queryForList(sql, new Object[0]);
    }

    /**
     * 获取当前数据库名称
     */
    public String getCurrentDatabase() throws SQLException {
        try (Connection conn = getConnection()) {
            return conn.getCatalog();
        }
    }

    /**
     * 获取数据库表列表
     */
    public List<Map<String, Object>> getTableList() throws SQLException {
        String database = getCurrentDatabase();
        String sql = "SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.TABLES " +
                "WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'";
        return queryForList(sql, database);
    }

    /**
     * 获取表字段信息
     */
    public List<Map<String, Object>> getTableColumns(String tableName) throws SQLException {
        String database = getCurrentDatabase();
        String sql = "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_COMMENT, IS_NULLABLE, " +
                "COLUMN_KEY, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH " +
                "FROM information_schema.COLUMNS " +
                "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? " +
                "ORDER BY ORDINAL_POSITION";
        return queryForList(sql, database, tableName);
    }

    /**
     * 关闭资源
     */
    public static void closeResources(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
        } catch (SQLException e) {
            // 忽略关闭异常
        }
        try {
            if (stmt != null) stmt.close();
        } catch (SQLException e) {
            // 忽略关闭异常
        }
        try {
            if (conn != null) conn.close();
        } catch (SQLException e) {
            // 忽略关闭异常
        }
    }
} 